package com.jeecg.o2o.torder.controller;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.jeecgframework.core.beanvalidator.BeanValidators;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.ExceptionUtil;
import org.jeecgframework.core.util.MyBeanUtils;
import org.jeecgframework.core.util.ResourceUtil;
import org.jeecgframework.jwt.util.ResponseMessage;
import org.jeecgframework.jwt.util.Result;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.vo.NormalExcelConstants;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.system.service.SystemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.UriComponentsBuilder;

import com.alibaba.fastjson.JSONArray;
import com.jeecg.o2o.businesses.entity.TbBusinessesEntity;
import com.jeecg.o2o.businesses.service.TbBusinessesServiceI;
import com.jeecg.o2o.statusbar.entity.StatusbarEntity;
import com.jeecg.o2o.statusbar.service.StatusbarServiceI;
import com.jeecg.o2o.tbimage.service.TbimageServiceI;
import com.jeecg.o2o.torder.entity.TorderEntity;
import com.jeecg.o2o.torder.service.TorderServiceI;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

/**   
 * @Title: Controller  
 * @Description: 全局订单不区分商家
 * @author onlineGenerator
 * @date 2019-05-30 14:57:33
 * @version V1.0   
 *
 */
@Api(value="Torder",description="全局订单不区分商家",tags="torderController")
@Controller
@RequestMapping("/torderController")
public class TorderController extends BaseController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(TorderController.class);

	@Autowired
	private TorderServiceI torderService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private Validator validator;
	@Autowired
	private TbBusinessesServiceI tbBusinessesService;
	@Autowired
	private TbimageServiceI tbimageServiceI;
	@Autowired
	private StatusbarServiceI statusbarService;


	/**
	 * 全局订单不区分商家列表 页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "list")
	public ModelAndView list(HttpServletRequest request) {
		return new ModelAndView("com/jeecg/o2o.torder/torderList");
	}

	/**
	 * easyui AJAX请求数据
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 * @param user
	 */
	@RequestMapping(params = "datagrid")
	public void datagrid(TorderEntity torder,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(TorderEntity.class, dataGrid);
		//查询条件组装器
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, torder, request.getParameterMap());
		cq.add();
		this.torderService.getDataGridReturn(cq, true);
		TagUtil.datagrid(response, dataGrid);
	}
	
	/**
	 * 删除全局订单不区分商家
	 * 
	 * @return
	 */
	@RequestMapping(params = "doDel")
	@ResponseBody
	public AjaxJson doDel(TorderEntity torder, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		torder = systemService.getEntity(TorderEntity.class, torder.getId());
		message = "全局订单不区分商家删除成功";
		try{
			torderService.delete(torder);
			systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			e.printStackTrace();
			message = "全局订单不区分商家删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	
	/**
	 * 批量删除全局订单不区分商家
	 * 
	 * @return
	 */
	 @RequestMapping(params = "doBatchDel")
	@ResponseBody
	public AjaxJson doBatchDel(String ids,HttpServletRequest request){
		String message = null;
		AjaxJson j = new AjaxJson();
		message = "全局订单不区分商家删除成功";
		try{
			for(String id:ids.split(",")){
				TorderEntity torder = systemService.getEntity(TorderEntity.class, 
				Integer.parseInt(id)
				);
				torderService.delete(torder);
				systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
			}
		}catch(Exception e){
			e.printStackTrace();
			message = "全局订单不区分商家删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}


	/**
	 * 添加全局订单不区分商家
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "doAdd")
	@ResponseBody
	public AjaxJson doAdd(TorderEntity torder, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		message = "全局订单不区分商家添加成功";
		try{
			torderService.save(torder);
			systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			e.printStackTrace();
			message = "全局订单不区分商家添加失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	
	/**
	 * 更新全局订单不区分商家
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "doUpdate")
	@ResponseBody
	public AjaxJson doUpdate(TorderEntity torder, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		message = "全局订单不区分商家更新成功";
		TorderEntity t = torderService.get(TorderEntity.class, torder.getId());
		try {
			MyBeanUtils.copyBeanNotNull2Bean(torder, t);
			torderService.saveOrUpdate(t);
			systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
		} catch (Exception e) {
			e.printStackTrace();
			message = "全局订单不区分商家更新失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	

	/**
	 * 导入功能跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "upload")
	public ModelAndView upload(HttpServletRequest req) {
		req.setAttribute("controller_name","torderController");
		return new ModelAndView("common/upload/pub_excel_upload");
	}
	
	/**
	 * 导出excel
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(params = "exportXls")
	public String exportXls(TorderEntity torder,HttpServletRequest request,HttpServletResponse response
			, DataGrid dataGrid,ModelMap modelMap) {
		CriteriaQuery cq = new CriteriaQuery(TorderEntity.class, dataGrid);
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, torder, request.getParameterMap());
		List<TorderEntity> torders = this.torderService.getListByCriteriaQuery(cq,false);
		modelMap.put(NormalExcelConstants.FILE_NAME,"全局订单不区分商家");
		modelMap.put(NormalExcelConstants.CLASS,TorderEntity.class);
		modelMap.put(NormalExcelConstants.PARAMS,new ExportParams("全局订单不区分商家列表", "导出人:"+ResourceUtil.getSessionUser().getRealName(),
			"导出信息"));
		modelMap.put(NormalExcelConstants.DATA_LIST,torders);
		return NormalExcelConstants.JEECG_EXCEL_VIEW;
	}
	/**
	 * 导出excel 使模板
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(params = "exportXlsByT")
	public String exportXlsByT(TorderEntity torder,HttpServletRequest request,HttpServletResponse response
			, DataGrid dataGrid,ModelMap modelMap) {
    	modelMap.put(NormalExcelConstants.FILE_NAME,"全局订单不区分商家");
    	modelMap.put(NormalExcelConstants.CLASS,TorderEntity.class);
    	modelMap.put(NormalExcelConstants.PARAMS,new ExportParams("全局订单不区分商家列表", "导出人:"+ResourceUtil.getSessionUser().getRealName(),
    	"导出信息"));
    	modelMap.put(NormalExcelConstants.DATA_LIST,new ArrayList());
    	return NormalExcelConstants.JEECG_EXCEL_VIEW;
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping(params = "importExcel", method = RequestMethod.POST)
	@ResponseBody
	public AjaxJson importExcel(HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			MultipartFile file = entity.getValue();// 获取上传文件对象
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(1);
			params.setNeedSave(true);
			try {
				List<TorderEntity> listTorderEntitys = ExcelImportUtil.importExcel(file.getInputStream(),TorderEntity.class,params);
				for (TorderEntity torder : listTorderEntitys) {
					torderService.save(torder);
				}
				j.setMsg("文件导入成功！");
			} catch (Exception e) {
				j.setMsg("文件导入失败！");
				logger.error(ExceptionUtil.getExceptionMessage(e));
			}finally{
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return j;
	}
	
	@RequestMapping(method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value="全局订单不区分商家列表信息",produces="application/json",httpMethod="GET")
	public ResponseMessage<List<TorderEntity>> list() {
		List<TorderEntity> listTorders=torderService.getList(TorderEntity.class);
		return Result.success(listTorders);
	}
	
	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value="根据ID获取全局订单不区分商家信息",notes="根据ID获取全局订单不区分商家信息",httpMethod="GET",produces="application/json")
	public ResponseMessage<?> get(@ApiParam(required=true,name="id",value="ID")@PathVariable("id") String id) {
		TorderEntity task = torderService.get(TorderEntity.class, id);
		if (task == null) {
			return Result.error("根据ID获取全局订单不区分商家信息为空");
		}
		return Result.success(task);
	}

	@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	@ApiOperation(value="创建全局订单不区分商家")
	public ResponseMessage<?> create(@ApiParam(name="全局订单不区分商家对象")@RequestBody TorderEntity torder, UriComponentsBuilder uriBuilder) {
		//调用JSR303 Bean Validator进行校验，如果出错返回含400错误码及json格式的错误信息.
		Set<ConstraintViolation<TorderEntity>> failures = validator.validate(torder);
		if (!failures.isEmpty()) {
			return Result.error(JSONArray.toJSONString(BeanValidators.extractPropertyAndMessage(failures)));
		}

		//保存
		try{
			torderService.save(torder);
		} catch (Exception e) {
			e.printStackTrace();
			return Result.error("全局订单不区分商家信息保存失败");
		}
		return Result.success(torder);
	}

	@RequestMapping(value = "/{id}", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	@ApiOperation(value="更新全局订单不区分商家",notes="更新全局订单不区分商家")
	public ResponseMessage<?> update(@ApiParam(name="全局订单不区分商家对象")@RequestBody TorderEntity torder) {
		//调用JSR303 Bean Validator进行校验，如果出错返回含400错误码及json格式的错误信息.
		Set<ConstraintViolation<TorderEntity>> failures = validator.validate(torder);
		if (!failures.isEmpty()) {
			return Result.error(JSONArray.toJSONString(BeanValidators.extractPropertyAndMessage(failures)));
		}

		//保存
		try{
			torderService.saveOrUpdate(torder);
		} catch (Exception e) {
			e.printStackTrace();
			return Result.error("更新全局订单不区分商家信息失败");
		}

		//按Restful约定，返回204状态码, 无内容. 也可以返回200状态码.
		return Result.success("更新全局订单不区分商家信息成功");
	}

	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
	@ResponseStatus(HttpStatus.NO_CONTENT)
	@ApiOperation(value="删除全局订单不区分商家")
	public ResponseMessage<?> delete(@ApiParam(name="id",value="ID",required=true)@PathVariable("id") String id) {
		logger.info("delete[{}]" + id);
		// 验证
		if (StringUtils.isEmpty(id)) {
			return Result.error("ID不能为空");
		}
		try {
			torderService.deleteEntityById(TorderEntity.class, id);
		} catch (Exception e) {
			e.printStackTrace();
			return Result.error("全局订单不区分商家删除失败");
		}

		return Result.success();
	}
	
	@RequestMapping(value = "/orderlist", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "根据员工id获取所有的订单列表", produces = "application/json;charset=UTF-8", httpMethod = "POST")
	public ResponseMessage<List<TorderEntity>> orderlist(@ApiParam(name = "商户实体信息") @RequestBody TorderEntity torderEntity,
			HttpServletRequest request, HttpServletResponse response) throws Exception {

		List<TorderEntity> task = torderService.findObjForJdbc(" select * from torder where userid="+torderEntity.getUserid()+" order by createdate", 1, 10, TorderEntity.class);//("from TorderEntity where userid=? order by createdate", TorderEntity.getUserid());
		for(TorderEntity orderEntity:task){
			List<TbBusinessesEntity> TbBusinessesEntitylist=tbBusinessesService.findHql("from TbBusinessesEntity where id=?", torderEntity.getRestaurantid());
			if(TbBusinessesEntitylist!=null&&TbBusinessesEntitylist.size()>0){
				TbBusinessesEntity TbBusinessesEntity=TbBusinessesEntitylist.get(0);
				orderEntity.setRestaurant_image_code(TbBusinessesEntity.getLogocode());
				orderEntity.setRestaurant_name(TbBusinessesEntity.getName());
			}
			
			List<StatusbarEntity> StatusbarEntitylist=statusbarService.findHql("from StatusbarEntity where id=?", orderEntity.getStatusbarid());
			if(StatusbarEntitylist!=null&&StatusbarEntitylist.size()>0){
				StatusbarEntity StatusbarEntity=StatusbarEntitylist.get(0);
				orderEntity.setStatus_bar(StatusbarEntity);
			}
		}
		if (task == null) {
			return Result.error("根据ID获取平台使用用户信息为空");
		}
		return Result.success(task);

	}
}
